package com.ddz.controller;

import com.ddz.model.LoginMessage;
import com.ddz.model.User;
import com.ddz.service.UserloginService;
import org.json.JSONObject;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/login")
public class UserloginServlet extends HttpServlet {

    private UserloginService userloginService = new UserloginService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 接收客户发送的账号和密码
        String username = request.getParameter("uid");
        String password = request.getParameter("upwd");

        // 判断玩家是否已经登录
        ServletContext servletContext = getServletContext();
        List<HttpSession> sessionList = (List<HttpSession>) servletContext.getAttribute("sessionList");
        if (sessionList!= null) {
            for (HttpSession s : sessionList) {
                // 判断所有会话中是否存在目标玩家
                User user = (User) s.getAttribute("User");
                if ((user == null)?false : user.getUserId().equals(username)){
                    // 返回错误消息
                    LoginMessage loginMessage = new LoginMessage(100,"此账号已经登录！请1分钟后尝试！");
                    request.setAttribute("loginMessage", loginMessage);
                    request.getRequestDispatcher("login.jsp").forward(request, response);
                    return;
                }
            }
        }
        // 调用服务方法
        LoginMessage loginMessage = userloginService.Login(username, password);
        // 判断是否登录成功
        if (loginMessage.getStatus() == 200){
            // 存入User对象
            System.out.println("用户已登录："+username+" "+password);
            JSONObject jsonObject = loginMessage.getJsonObject();
            User user = new User(jsonObject.getString("userID"),jsonObject.getString("password"),jsonObject.getString("nickname"));
            user.setScore(jsonObject.getInt("score"));
            // 保存玩家对象
            request.getSession().setAttribute("User", user);
            response.sendRedirect("./index.jsp");
        }
        else if(loginMessage.getStatus() == 100){
            request.setAttribute("loginMessage", loginMessage);
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }

    }
}
